#!/usr/bin/env python

import datetime
import glob
import math
import os
import os.path as osp
import subprocess
import sys

import cv2

import jsk_recognition_utils


here = osp.dirname(osp.realpath(__file__))


PACKAGES = [
    'jsk_rviz_plugins',
    'jsk_rqt_plugins',
]


def get_gallery():
    content = []
    for pkg in PACKAGES:
        # TODO(wkentaro): Scrape pacakge.xml only once by creating a class.
        from bs4 import BeautifulSoup
        with open(osp.join(pkg, 'package.xml')) as f:
            soup = BeautifulSoup(f.read(), 'lxml')
        website_url = soup.find('url', type='website')

        imgs = []
        for ext in ['*.png', '*.jpg']:
            pattern = osp.join(here, 'doc', pkg, 'plugins/images', ext)
            for fname in glob.glob(pattern):
                img = cv2.imread(fname)
                scale = math.sqrt(1. * 200 * 200 / img.shape[0] / img.shape[1])
                img = cv2.resize(img, None, None, fx=scale, fy=scale)
                imgs.append(img)
                if len(imgs) >= 15:
                    break
        if not imgs:
            continue

        cols = 5
        rows = max(len(imgs) // cols, 1)
        tiled = jsk_recognition_utils.get_tile_image(
            imgs, tile_shape=(cols, rows), margin_color=[255, 255, 255])
        fname = osp.join(here, '.readme/gallery_%s.jpg' % pkg)
        if not osp.exists(osp.dirname(fname)):
            os.makedirs(osp.dirname(fname))
        cv2.imwrite(fname, tiled)
        doc_url = website_url.text if website_url else ''
        content.append('### [%s](%s)' % (pkg, doc_url))
        content.append('')
        content.append('[![](%s)](%s)' % (osp.relpath(fname, here), doc_url))
        content.append('')
    return '\n'.join(content)


def get_deb_status_table():
    cmd = 'rosrun jsk_tools generate_deb_status_table.py jsk_visualization'
    return subprocess.check_output(cmd, shell=True).strip()


template = '''\
<!--
    DO NOT EDIT THIS FILE BY HAND.

    This file is automatically generated by {SCRIPT} at {TIMESTAMP}.
-->

jsk\_visualization
=================

 [![Build Status](https://travis-ci.org/jsk-ros-pkg/jsk_visualization.svg?branch=master)](https://travis-ci.org/jsk-ros-pkg/jsk_visualization)
[![Read the Docs](https://readthedocs.org/projects/pip/badge/?version=latest)](https://jsk-visualization.readthedocs.org)

jsk visualization ros package.

See [read the docs](http://jsk-visualization.readthedocs.org/en/latest/).


Gallery
-------

{GALLERY}


Deb build status
----------------

{DEB_STATUS_TABLE}
'''


def main():
    sys.stdout.write(
        template.format(
            SCRIPT=osp.realpath(__file__),
            TIMESTAMP=datetime.datetime.now().isoformat(),
            DEB_STATUS_TABLE=get_deb_status_table(),
            GALLERY=get_gallery(),
        )
    )


if __name__ == '__main__':
    main()
